package cn.iocoder.yudao.module.erp.service.business.produce.defectiveitems;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.business.produce.defectiveitems.vo.DefectiveItemsPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.business.produce.defectiveitems.vo.DefectiveItemsSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.business.produce.defectiveitems.DefectiveItemsDO;
import cn.iocoder.yudao.module.erp.dal.mysql.business.produce.defectiveitems.DefectiveItemsMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.DEFECTIVE_ITEMS_NOT_EXISTS;

/**
 * 不良品项 Service 实现类
 *
 * @author 奥特曼
 */
@Service
@Validated
public class DefectiveItemsServiceImpl implements DefectiveItemsService {

    @Resource
    private DefectiveItemsMapper defectiveItemsMapper;

    @Override
    public Long createDefectiveItems(DefectiveItemsSaveReqVO createReqVO) {
        // 插入
        DefectiveItemsDO defectiveItems = BeanUtils.toBean(createReqVO, DefectiveItemsDO.class);
        defectiveItemsMapper.insert(defectiveItems);
        // 返回
        return defectiveItems.getId();
    }

    @Override
    public void updateDefectiveItems(DefectiveItemsSaveReqVO updateReqVO) {
        // 校验存在
        validateDefectiveItemsExists(updateReqVO.getId());
        // 更新
        DefectiveItemsDO updateObj = BeanUtils.toBean(updateReqVO, DefectiveItemsDO.class);
        defectiveItemsMapper.updateById(updateObj);
    }

    @Override
    public void deleteDefectiveItems(Long id) {
        // 校验存在
        validateDefectiveItemsExists(id);
        // 删除
        defectiveItemsMapper.deleteById(id);
    }

    private void validateDefectiveItemsExists(Long id) {
        if (defectiveItemsMapper.selectById(id) == null) {
            throw exception(DEFECTIVE_ITEMS_NOT_EXISTS);
        }
    }

    @Override
    public DefectiveItemsDO getDefectiveItems(Long id) {
        return defectiveItemsMapper.selectById(id);
    }

    @Override
    public PageResult<DefectiveItemsDO> getDefectiveItemsPage(DefectiveItemsPageReqVO pageReqVO) {
        return defectiveItemsMapper.selectPage(pageReqVO);
    }

}